package com.aviator.detective.script.method;

import com.aviator.detective.script.aviator.ExpressionRunException;
import com.google.common.base.Splitter;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorBoolean;
import com.googlecode.aviator.runtime.type.AviatorObject;
import org.apache.commons.collections.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * array contains
 * 名单判定处理
 */
public class ArrayContainsMethod extends AbstractFunction {

    @Override
    public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2) {
        try {
            String arrayStr = FunctionUtils.getStringValue(arg1,env);
            String containsStr = FunctionUtils.getStringValue(arg2,env);
            if (arrayStr.startsWith("[") && arrayStr.endsWith("]")){
                arrayStr = arrayStr.substring(1,arrayStr.length()-1);
            }
            if (arrayStr.startsWith("{") && arrayStr.endsWith("}")){
                arrayStr = arrayStr.substring(1,arrayStr.length()-1);
            }
            List<String> itemList = Splitter.on(",").trimResults().splitToList(arrayStr);
            if (CollectionUtils.isEmpty(itemList)){
                return AviatorBoolean.FALSE;
            }
            if (itemList.contains(containsStr)){
                return AviatorBoolean.TRUE;
            }
            return AviatorBoolean.FALSE;
        }catch (Exception e){
            e.printStackTrace();
            throw new ExpressionRunException("arrayContains method execute exception");
        }

    }

    public String getName() {
        return "arrayContains";
    }
}
